package com.xinwei.leetcode.链表;
// https://leetcode-cn.com/problems/merge-two-sorted-lists/
public class _21_合并两个有序链表 {
    // 迭代
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        ListNode node1 = list1;
        ListNode node2 = list2;
        ListNode node;
        if (node1.val >= node2.val) {
            node = node2;
            node2 = node2.next;
        }else {
            node = node1;
            node1 = node1.next;
        }
        ListNode head = node;
        while (node1 != null || node2 != null) {
            if (node1 == null) {
                node.next = node2;
                break;
            }
            if (node2 == null) {
                node.next = node1;
                break;
            }
            if (node1.val <= node2.val) {
                node.next = node1;
                node = node.next;
                node1 = node1.next;
            }else {
                node.next = node2;
                node = node.next;
                node2 = node2.next;
            }
        }
        return head;
    }

    // 递归
    public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }else if (l2 == null) {
            return l1;
        }else if (l1.val < l2.val) {
            l1.next = mergeTwoLists1(l1.next, l2);
            return l1;
        }else {
            l2.next = mergeTwoLists1(l1, l2.next);
            return l2;
        }
    }


}
